<template>
  <div class="YUploadVideoSingle" :style="myStyle">
    <el-upload
      ref="yUpload"
      v-if="isVideoNull && !disabled"
      action=""
      :show-file-list="false"
      :http-request="doUpload"
      :on-remove="handleRemove"
      :on-change="onChange"
      :limit="1"
      accept="video/mp4"
      :auto-upload="false">
      <el-link type="primary" slot="default" underline>添加相关视频……</el-link>
      <div v-if="showTip" slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过{{limitSize}}mb</div>
    </el-upload>
    <template v-if="!isVideoNull">
      <el-link type="success" class="video-name" :underline="false" @click="handlePreview(myVideo)">
        {{myVideo.videoName}}
        <i class="el-icon-video-play"></i>
      </el-link>
      <el-popconfirm
        v-if="showDelete && !disabled"
        title="是否确认删除该视频？"
        style="margin-left: 10px"
        @confirm="handleRemove(myVideo)">
        <el-link slot="reference" type="danger" :underline="false" @click="handleRemove(myVideo)">
          <i class="el-icon-delete"></i>
        </el-link>
      </el-popconfirm>
    </template>
    <el-dialog
      :visible.sync="previewVisible"
      @closed="closePreview"
      append-to-body>
      <video v-if="!isVideoNull"
             :src="generateMediaUrl({
              fileOpenUrl: myVideo.videoUrl
             })" controls autoplay style="width: 100%; max-height: 80vh;"></video>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "YUploadVideoSingle",
  inject: ['File2ArrayBuffer', 'generateMediaUrl', 'defaultUploadChange'],
  props:{
    disabled:{
      type: Boolean,
      default: false
    },
    showDelete:{
      type: Boolean,
      default: false
    },
    businessSysModuleCode: String,
    showTip:{
      type: Boolean,
      default: true
    },
    limitSize:{
      type: Number,
      default: 10
    },
    width:{
      type: String,
      default: 'auto'
    },
    model:{
      type: Object
    },
    customStyle:{
      default: () => ({})
    }
  },
  computed:{
    isVideoNull(){
      return Object.values(this.myVideo).every(v => !v);
    },
    myStyle(){
      if(this.width !== 'auto'){
        return Object.assign({}, this.customStyle, {width: this.width})
      }else{
        return Object.assign({}, this.customStyle)
      }
    }
  },
  data(){
    return{
      myVideo: {
        videoUrl: '',
        videoName: '',
        videoAttachmentId: ''
      },
      videoList: [],
      //displayFile: null,
      previewVisible: false,
      lock: false,
    }
  },
  mounted(){
  },
  methods:{
    emitData(type, file){
      this.lock = true;
      if(!this.isVideoNull){
        this.model.videoName = this.myVideo.videoName;
        this.model.videoUrl = this.myVideo.videoUrl;
      }else{
        this.model.videoName = "";
        this.model.videoUrl = "";
      }
      this.lock = false;
      this.$emit('update');
      this.$emit('updateExactly', {type, file});
    },
    doUpload(){

    },
    handlePreview(file){
      //this.displayFile = file;
      this.previewVisible = true;
    },
    closePreview(){
      //this.displayFile = null;
    },
    // 上传按钮
    async onChange(fileObj, fileList) {
      if(!fileObj.name.endsWith('mp4') && !fileObj.name.endsWith('MP4')){
        this.$message({
          type: 'warning',
          message: `仅支持上传mp4格式的视频`
        });
        this.$refs['yUpload'].clearFiles();
        return;
      }
      if(fileObj.size > this.limitSize * 1024 * 1024){
        this.$message({
          type: 'warning',
          message: `文件大小超出限制：${this.limitSize}mb`
        });
        this.$refs['yUpload'].clearFiles();
        return;
      }
      this.defaultUploadChange(fileObj, info => {
        let newImg = {
          id: info.id,
          videoAttachmentId: info.id,
          uid: fileObj.uid,
          videoName: fileObj.name,
          videoUrl: info.fileOpenUrl
        };
        this.$set(this, 'myVideo', newImg);
        this.emitData('add', newImg)
      });
    },
    remove(){
      let delId = this.myVideo.videoAttachmentId;
      delId && this.$yAxios({
        url: this.$api.common.removeAttachment,
        data:{
          id: delId
        }
      })
    },
    handleRemove(file, fileList){
      this.remove();
      this.$set(this, 'myVideo', {
        videoUrl: '',
        videoName: '',
        videoAttachmentId: ''
      });
      this.emitData('delete', file);
    },
    //TODO,由于视频文件跨域，这个视频缩略图就不做了
    getVideoImgBlob(url) {
      return new Promise(function (resolve, reject) {
        let dataURL = '';
        let video = document.createElement("video");
        video.setAttribute('crossOrigin', 'anonymous');//处理跨域
        video.setAttribute('src', url);
        video.currentTime = 3;
        video.addEventListener('canplay', function () {
          let canvas = document.createElement("canvas"),
              width = 400, //canvas的尺寸和图片一样
              height = 240;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(video, 0, 0, width, height, 0, 0, width, height); //绘制canvas
          let base64 =  canvas.toDataURL('image/png')/*.replace('image/png', 'image/octet-stream')*/;
          resolve(base64);
          /*canvas.toBlob(blob => {
            resolve(blob);
          }, 'image/png'); //转换为blob*/
        });
      })
    }
  },
  watch:{
    'model.videoName': {
      handler(){
        if(!this.lock){
          this.myVideo = Object.gain(this.model, ['videoName', 'videoUrl', 'videoAttachmentId']);
          if(!this.myVideo.videoName && this.myVideo.videoUrl){
            this.myVideo.videoName = this.myVideo.videoUrl.split('/').pop();
          }
        }
      },
      immediate: true
    },
    'model.videoUrl': {
      handler(){
        if(!this.lock){
          this.myVideo = Object.gain(this.model, ['videoName', 'videoUrl', 'videoAttachmentId']);
          if(!this.myVideo.videoName && this.myVideo.videoUrl){
            this.myVideo.videoName = this.myVideo.videoUrl.split('/').pop();
          }
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped lang="less">
.YUploadVideoSingle{
  line-height: 1.2;
  display: flex;
  justify-content: center;
  /deep/.el-upload{
    width: 100%;
  }
  /deep/.video-name{
    word-break: break-all;
  }
}
</style>